package com.example.aquanliangblogscan.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.example.aquanliangblogscan.entity.Article;
import com.example.aquanliangblogscan.util.AsyncScanBlogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author guochaobin
 * @date 2022/9/7
 */
@Service
@Slf4j
public class ScanBlogServiceImpl implements ScanBlogService {
    @Autowired
    private AsyncScanBlogUtil asyncScanBlogUtil;
    public static HashMap<String, Object>[] maps;

    public static CountDownLatch latch;

    /**
     * 扫描所有博客数据并下载到excel
     */
    @Override
    public void getDataToExcel(String savePath) {
        //    解析url地址 获取页码 处理第一页顺便获得最后页码数
        Document document = null;
        try {
            document = Jsoup.parse(new URL("https://www.aquanliang.com/blog"), 10000);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<Element> spans = asyncScanBlogUtil.getSpans(document);
        latch = new CountDownLatch(1);
        int page = getPage(document);
        maps = new HashMap[page];
        Map<String, Object> pageOne = asyncScanBlogUtil.getDataAndGenerateOnePage(1, "https://www.aquanliang.com/blog", page);
        try {
            latch.await(6, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
//         TODO: 2022/9/6 1、看看能不能多线程 2、加log日志
//        getPictures(spans, 1);


        latch = new CountDownLatch(page - 1);
        for (int i = 2; i <= page; i++) {
            Map<String, Object> map = asyncScanBlogUtil.getDataAndGenerateOnePage(i, "https://www.aquanliang.com/blog" + "/page/" + i, page);
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println();
        List<Map<String, Object>> list = Arrays.asList(maps);
        Boolean result = wriExcel(list, savePath);
        if (result.equals(Boolean.TRUE)) {
            log.info("excel写入完成,文件在 {}", savePath);
        } else {
            log.error("excel写入失败");
        }
    }

    /**
     * * 过滤并获取文章的那一堆span
     *
     * @param document
     * @return
     */


    /**
     * 最终把所有页 分多个sheet写入excel文件*
     *
     * @param list
     */
    private Boolean wriExcel(List<Map<String, Object>> list, String savePath) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        OutputStream outputStream = null;
        try {
//            workbook.write(Files.newOutputStream(Paths.get("D:\\blogs.xls")));
            outputStream = Files.newOutputStream(Paths.get(savePath));
            workbook.write(outputStream);
            return Boolean.TRUE;
            //加图片
//            workbook.addPicture()
        } catch (IOException e) {
            e.printStackTrace();
            return Boolean.FALSE;
        } finally {
            try {
                if (workbook != null)
                    workbook.close();
                if (outputStream!=null)
                    outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获取总页码数*
     *
     * @param document
     * @return
     */
    private int getPage(Document document) {
        Elements ul = document.getElementsByTag("ul");
        List<Element> lis = null;
        try {
            lis = ul.get(1).getElementsByTag("li").stream().filter(
                    li -> li.hasClass("ant-pagination-item")).collect(Collectors.toList());

            Element pageElement = lis.get(lis.size() - 1);
            String title = pageElement.attr("title");
            return Integer.parseInt(title);
        } catch (Exception e) {
            log.error("连接超时请重试", e);
        }
        return 0;
    }
}
